﻿using System;
using System.Collections.Generic;
using System.Web.Services;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using Adex;
using Telerik.Web.UI;
using MediaMonitor.Common;
using System.Collections;

namespace MediaMonitor.Users
{
    public partial class Report_TVCR_Filter2 : Adex.BasePage
    {
        DateTime sDate = DateTime.MinValue, eDate = DateTime.MinValue;
        private int mediaTypeCode = 0;
        private string mediaCodes = "";
        private int programCode = 0;
        private int sectorCode = 0, subSectorCode = 0, subSector2Code = 0, categoryCode = 0;
        int advertiserCode = 0, brandCode = 0, productCode = 0, versionCode = 0, agencyCode = 0;
        int sTime = 0, eTime = 0;
        int sLength = 0, eLength = 0;
        int posInBreak = 0;
        int sPrice = 0, ePrice = 0;
        bool firstAppearanceOnly = false;
        bool DownloadOnly = false;
        bool DownloadOnlyProduct = false;
        bool DownloadOnlyAdvertiser = false;

        private string sector = "", subsector = "", category = "", advertiser = "", agency = "";
        private string product = "", version = "";

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                Utility.AddDateControlToPage(this.Page);


                SetCalendarDates();
                //calS.SelectedDate = DateTime.Now.Date;
                //calE.SelectedDate = DateTime.Now.Date;

                FillMediaTypes();
                FillPrograms(1);

                FillSectors();
                FillSubSectors();
                FillCategories();
                FillAdvertisers(1);
                FillAgencies(1);
                Session["TVCRUserWriteProductName"] = 0;
                Session["TVCRVerUserWriteProductName"] = 0;

                Session["TVCRUserWriteProductNameText"] = "";
                Session["TVCRVerUserWriteProductNameText"] = "";
               
            }
        }

        private void SetCalendarDates()
        {

            DataTable dt = SPs.RfdateNewCommercial().GetDataSet().Tables[0];//CommercialLog1.Query().DISTINCT().SetSelectList("RFDate,preliminaryData").ExecuteDataSet().Tables[0];
                //DataTable dt = SPs.GetDateOfTVCR().GetDataSet().Tables[0];

                foreach (DataRow dr in dt.Rows)
                {
                    if (dr["RFDate"].ToString() != "")
                    {
                        RadCalendarDay d1 = new RadCalendarDay(calS);
                        d1.Date = Utility.ToDateTime(Utility.GetDateFromNumber(dr["RFDate"].ToString()));
                        d1.IsDisabled = false;
                        d1.IsSelectable = true;


                        if (Utility.ToBool(dr["preliminaryData"]))
                            d1.ItemStyle.BackColor = System.Drawing.Color.Orange;
                        else
                            d1.ItemStyle.BackColor = System.Drawing.Color.PowderBlue;
                        d1.ItemStyle.ForeColor = System.Drawing.Color.White;
                        calS.SpecialDays.Add(d1);

                        RadCalendarDay d2 = new RadCalendarDay(calE);
                        d2.Date = Utility.ToDateTime(Utility.GetDateFromNumber(dr["RFDate"].ToString()));
                        d2.IsDisabled = false;
                        d2.IsSelectable = true;

                        if (Utility.ToBool(dr["preliminaryData"]))
                            d2.ItemStyle.BackColor = System.Drawing.Color.Orange;
                        else
                            d2.ItemStyle.BackColor = System.Drawing.Color.PowderBlue;
                        d2.ItemStyle.ForeColor = System.Drawing.Color.White;


                        calE.SpecialDays.Add(d2);
                    }

                }

            
                  


        }


        protected void calS_ViewChanged(object sender, EventArgs e)
        {
            for (DateTime dt = calS.CalendarView.ViewStartDate; dt <= calS.CalendarView.ViewEndDate; dt.AddDays(1))
            {

            }
        }

        private static DataSet GetLookupDataSet()
        {

            //if (HttpContext.Current.Cache["dsLookUpByUser_TVCR_" + AppUser.CurrUserID.ToString()] == null)
            //{
            //Get Lookup Tables filtered by User / Company settings

            //DataSet ds = SPs.SpGetReportFilterLookupTables(AppUser.CurrUserID).GetDataSet();
            DataSet ds = SPs.GetLookupTables2(AppUser.CurrUserID, "TVCR").GetDataSet();
            ds.Tables[0].TableName = "MediaType";
            ds.Tables[1].TableName = "Media";
          
            ds.Tables[3].TableName = "Advertiser";
            ds.Tables[4].TableName = "Brand";
            ds.Tables[5].TableName = "Sector";
            ds.Tables[6].TableName = "SubSector";
            ds.Tables[7].TableName = "Category";
            ds.Tables[8].TableName = "Product";
            ds.Tables[9].TableName = "ProdVersion";
           
             //HttpContext.Current.Cache.Insert("dsLookUpByUser_TVCR_" + AppUser.CurrUserID.ToString(), ds, null, DateTime.Now.AddMinutes(60), System.Web.Caching.Cache.NoSlidingExpiration, System.Web.Caching.CacheItemPriority.Normal, null);


            return ds;

            //}
             //else
             //{
               // return ((DataSet)(HttpContext.Current.Cache["dsLookUpByUser_TVCR_" + AppUser.CurrUserID.ToString()]));
             //}
        }
        private static DataSet GetLookupDataSet(int mediaTypeCode)
        {
            DataSet ds1 = SPs.GetLookupTables3(AppUser.CurrUserID, "TVCR",mediaTypeCode).GetDataSet();
            ds1.Tables[0].TableName = "Program";
            ds1.Tables[1].TableName = "Agency";
            ds1.Tables[2].TableName = "Advertiser";
            return ds1;
        }


        #region FillLists


        private void FillSectors()
        {
            DataTable dt = GetLookupDataSet().Tables[5];

            string filter = "1=1";
            switch (lstMediaType.SelectedValue)
            {
                case "1":
                    {
                        filter += " AND MediaType = 'TVCR' AND  TV = 1";
                        break;
                    }

                case "3":
                    {
                        filter += " AND MediaType = 'TVCR'  AND RD = 1";
                        break;
                    }
                case "5":
                    {
                        filter += " AND MediaType = 'TVCR'  AND CB = 1";
                        break;
                    }
                case "6":
                    {
                        filter += " AND MediaType = 'PR' AND PR = 1";
                        break;
                    }
                case "7":
                    {
                        filter += " AND MediaType = 'OD' AND OD = 1";
                        break;
                    }
                case "8":
                    {
                        filter += " AND MediaType = 'NS' AND NS = 1";
                        break;
                    }
            }

            string sort = "SectorName";

            DataView dv = new DataView(dt, filter, sort, DataViewRowState.OriginalRows);
            DataTable dtcolumns = dv.ToTable(true, "SectorCode", "SectorName");

            if (dtcolumns.Rows.Count > 0)
            {
                dtcolumns = RemoveDuplicateRows(dtcolumns, "SectorName");
                lstSector.DataSource = dtcolumns;
                lstSector.DataBind();
            }                     
             lstSector.Items.Insert(0, new ListItem("- ALL -", "0"));
        }


        public DataTable RemoveDuplicateRows(DataTable dTable, string colName)
        {
            Hashtable hTable = new Hashtable();
            ArrayList duplicateList = new ArrayList();

            //Add list of all the unique item value to hashtable, which stores combination of key, value pair.
            //And add duplicate item value in arraylist.
            foreach (DataRow drow in dTable.Rows)
            {
                if (hTable.Contains(drow[colName]))
                    duplicateList.Add(drow);
                else
                    hTable.Add(drow[colName], string.Empty);
            }

            //Removing a list of duplicate items from datatable.
            foreach (DataRow dRow in duplicateList)
                dTable.Rows.Remove(dRow);

            //Datatable which contains unique records will be return as output.
            return dTable;
        }
        public static DataTable RemoveDuplicateRows1(DataTable dTable, string colName)
        {
            Hashtable hTable = new Hashtable();
            ArrayList duplicateList = new ArrayList();

            //Add list of all the unique item value to hashtable, which stores combination of key, value pair.
            //And add duplicate item value in arraylist.
            foreach (DataRow drow in dTable.Rows)
            {
                if (hTable.Contains(drow[colName]))
                    duplicateList.Add(drow);
                else
                    hTable.Add(drow[colName], string.Empty);
            }

            //Removing a list of duplicate items from datatable.
            foreach (DataRow dRow in duplicateList)
                dTable.Rows.Remove(dRow);

            //Datatable which contains unique records will be return as output.
            return dTable;
        }
        private void FillSubSectors()
        {
            DataTable dt = GetLookupDataSet().Tables[6];

            string filter = "1=1";
            //switch (lstMediaType.SelectedValue)
            //{
            //    case "1":
            //        {
            //            filter += " AND MediaType = 'TVCR'  AND TV = 1";
            //            break;
            //        }

            //    case "3":
            //        {
            //            filter += " AND MediaType = 'TVCR'  AND RD = 1";
            //            break;
            //        }
            //    case "5":
            //        {
            //            filter += " AND MediaType = 'TVCR'  AND CB = 1";
            //            break;
            //        }
            //    case "6":
            //        {
            //            filter += " AND MediaType = 'PR' AND PR = 1";
            //            break;
            //        }
            //    case "7":
            //        {
            //            filter += " AND MediaType = 'OD' AND OD = 1";
            //            break;
            //        }
            //    case "8":
            //        {
            //            filter += " AND MediaType = 'NS' AND NS = 1";
            //            break;
            //        }
            //}

            filter += lstSector.SelectedValue != "0" ? " AND SectorCode=" + lstSector.SelectedValue : "";

            string sort = "SubSectorName";

            DataView dv = new DataView(dt, filter, sort, DataViewRowState.OriginalRows);

            DataTable dtcolumns = dv.ToTable(true, "SubSectorCode", "SubSectorName");

            if (dtcolumns.Rows.Count > 0)
            {
                dtcolumns = RemoveDuplicateRows(dtcolumns, "SubSectorName");

                lstSubSector.DataSource = dtcolumns;
                lstSubSector.DataBind();

                lstSubSector2.DataSource = dtcolumns;
                lstSubSector2.DataBind();
            }

            lstSubSector.Items.Insert(0, new ListItem("- ALL -", "0"));
            lstSubSector2.Items.Insert(0, new ListItem("- ALL -", "0"));
        }

        private void FillCategories()
        {
            DataTable dt = GetLookupDataSet().Tables[7];

            string filter = "1=1";
           
            
            
            
            //switch (lstMediaType.SelectedValue)
            //{
            //    case "1":
            //        {
            //            filter += " AND MediaType='TVCR' AND TV = 1";
            //            break;
            //        }

            //    case "3":
            //        {
            //            filter += " AND MediaType='TVCR' AND RD = 1";
            //            break;
            //        }
            //    case "5":
            //        {
            //            filter += " AND MediaType='TVCR' AND CB = 1";
            //            break;
            //        }
            //    case "6":
            //        {
            //            filter += " AND MediaType='PR' AND PR = 1";
            //            break;
            //        }
            //    case "7":
            //        {
            //            filter += " AND MediaType='OD' AND OD = 1";
            //            break;
            //        }
            //    case "8":
            //        {
            //            filter += " AND MediaType='NS' AND NS = 1";
            //            break;
            //        }
            //}

           // filter += lstSector.SelectedValue != "0" ? " AND SectorCode=" + lstSector.SelectedValue : "";
            filter += lstSubSector.SelectedValue != "0" ? " AND SubSectorCode=" + lstSubSector.SelectedValue : "";

            string sort = "CategoryName";

            DataView dv = new DataView(dt, filter, sort, DataViewRowState.OriginalRows);

            DataTable dtcolumns = dv.ToTable(true, "CategoryCode", "CategoryName");

            if (dtcolumns.Rows.Count > 0)
            {
                dtcolumns = RemoveDuplicateRows(dtcolumns, "CategoryName");
                lstCategory.DataSource = dtcolumns;
                lstCategory.DataBind();
            }
            lstCategory.Items.Insert(0, new ListItem("- ALL -", "0"));
        }

        private void FillAdvertisers(int mediaTypeCode)
        {
            DataTable dt = GetLookupDataSet(mediaTypeCode).Tables[2];

            string filter = "1=1";
            //switch (lstMediaType.SelectedValue)
            //{
            //    case "1":
            //        {
            //            filter += " AND MediaType='TVCR' AND TV = 1";
            //            break;
            //        }

            //    case "3":
            //        {
            //            filter += " AND MediaType='TVCR' AND RD = 1";
            //            break;
            //        }
            //    case "5":
            //        {
            //            filter += " AND MediaType='TVCR' AND CB = 1";
            //            break;
            //        }
            //    case "6":
            //        {
            //            filter += " AND MediaType='PR' AND PR = 1";
            //            break;
            //        }
            //    case "7":
            //        {
            //            filter += " AND MediaType='OD' AND OD = 1";
            //            break;
            //        }
            //    case "8":
            //        {
            //            filter += " AND MediaType='NS' AND NS = 1";
            //            break;
            //        }
            //}

            string sort = "AdvertiserName";

            DataView dv = new DataView(dt, filter, sort, DataViewRowState.OriginalRows);
            DataTable dtcolumns = dv.ToTable(true, "AdverTiserCode", "AdvertiserName");

              
                    dtcolumns = RemoveDuplicateRows(dtcolumns, "AdvertiserName");
                   lstAdvertiser.DataSource = dtcolumns;
                    lstAdvertiser.DataBind();
                
           

            lstAdvertiser.Items.Insert(0, new ListItem("- ALL -", "0"));
        }

        private void FillAgencies(int mediaTypeCode)
        {
            DataTable dt = GetLookupDataSet(mediaTypeCode).Tables[1];

            string filter = "1=1";
            //switch (lstMediaType.SelectedValue)
            //{
            //    case "1":
            //        {
            //            filter += " AND MediaType='TVCR' AND TV = 1";
            //            break;
            //        }

            //    case "3":
            //        {
            //            filter += " AND MediaType='TVCR' AND RD = 1";
            //            break;
            //        }
            //    case "5":
            //        {
            //            filter += " AND MediaType='TVCR' AND CB = 1";
            //            break;
            //        }
            //    case "6":
            //        {
            //            filter += " AND MediaType='PR' AND PR = 1";
            //            break;
            //        }
            //    case "7":
            //        {
            //            filter += " AND MediaType='OD' AND OD = 1";
            //            break;
            //        }
            //    case "8":
            //        {
            //            filter += " AND MediaType='NS' AND NS = 1";
            //            break;
            //        }
            //}
            string sort = "AgencyName";

            DataView dv = new DataView(dt, filter, sort, DataViewRowState.OriginalRows);
            DataTable dtcolumns = dv.ToTable(true, "AgencyCode", "AgencyName");

            
                dtcolumns = RemoveDuplicateRows(dtcolumns, "AgencyName");
                lstAgency.DataSource = dtcolumns;
                lstAgency.DataBind();
            
           
            lstAgency.Items.Insert(0, new ListItem("- ALL -", "0"));
        }

        protected void lstSector_Changed(object sender, EventArgs e)
        {
            FillSubSectors();
            FillCategories();

        }

        protected void lstSubSector_Changed(object sender, EventArgs e)
        {
            FillCategories();

        }

        #endregion


        #region Fill Media

        private void FillMediaTypes()
        {

            lstMediaType.DataSource = GetLookupDataSet().Tables["MediaType"];
            lstMediaType.DataBind();

            Utility.SelectListItemByText(lstMediaType, "TV");

            FillMedia(Utility.ToInt(lstMediaType.SelectedValue));

        }

        private void FillMedia(int MediaTypeCode)
        {


            if (MediaTypeCode > 0)
                lstMedia.DataSource = new DataView(GetLookupDataSet().Tables["Media"], "MediaTypeCode=" + MediaTypeCode.ToString(), "MediaName", DataViewRowState.OriginalRows);
            else
                lstMedia.DataSource = GetLookupDataSet().Tables["Media"];


            lstMedia.DataBind();


        }


        protected void lstMediaType_SelectedIndexChanged(object sender, EventArgs e)
        {
            FillMedia(Utility.ToInt(lstMediaType.SelectedValue));

            FillAdvertisers(Convert.ToInt32(lstMediaType.SelectedValue));
            FillAgencies(Convert.ToInt32(lstMediaType.SelectedValue));
            FillPrograms(Convert.ToInt32(lstMediaType.SelectedValue));

        }



        #endregion



        #region AutoComplete Functions
            

        [WebMethod]
        public static string[] AutoComplete_FillBrand(string prefixText, int count)
        {
            if (count == 0) { count = 10; }
            List<string> items = new List<string>(count);

            DataTable dt = GetLookupDataSet().Tables[4];

            string filter = "1=1 ";
            string filterwrite = "1=1 ";

            filter += " AND MediaType='TVCR' AND BrandName LIKE '" + prefixText + "%'";

            filterwrite += " AND MediaType='TVCR' AND BrandName ='" + prefixText + "'";
           

            if (dt.Rows.Count > 0)
            {
                dt = RemoveDuplicateRows1(dt, "BrandName");

            }
            DataRow[] drsUserWrite = dt.Select(filterwrite);
            try
            {
                if (drsUserWrite.Length == 1) //If user write and that item is in database
                {
                    HttpContext.Current.Session["TVCRUserWriteProductName"] = drsUserWrite[0][0];
                    HttpContext.Current.Session["TVCRUserWriteProductNameText"] = drsUserWrite[0][2];

                }
                else
                {
                    HttpContext.Current.Session["TVCRUserWriteProductName"] = -1;
                    HttpContext.Current.Session["TVCRUserWriteProductNameText"] = "";
                }
            }
            catch { }

            DataRow[] drs = dt.Select(filter);

            int counter = 0;
            foreach (DataRow dr in drs)
            {
                items.Add(AjaxControlToolkit.AutoCompleteExtender.CreateAutoCompleteItem(dr["BrandName"].ToString(), dr["BrandCode"].ToString()));


                if (++counter >= count) { break; }
            }

            return items.ToArray();
        }

        [WebMethod]
        public static string[] AutoComplete_FillProduct(string prefixText, int count, string contextKey)
        {
            //contextKey is brandCode


            string filter = "1=1 ";
            filter += " AND MediaType='TVCR' AND ProductName LIKE '" + prefixText + "%'";

            //get brand 

           

            if (count == 0) { count = 10; }
            List<string> items = new List<string>(count);

            DataTable dt = GetLookupDataSet().Tables[8];
           

            if (dt.Rows.Count > 0)
            {
                dt = RemoveDuplicateRows1(dt, "ProductName");
                
            }

            DataRow[] drs = dt.Select(filter);
            int counter = 0;
            foreach (DataRow dr in drs)
            {
                items.Add(AjaxControlToolkit.AutoCompleteExtender.CreateAutoCompleteItem(dr["ProductName"].ToString(), dr["ProductCode"].ToString()));


                if (++counter >= count) { break; }
            }

            return items.ToArray();
        }

        [WebMethod]
        public static string[] AutoComplete_FillVersion(string prefixText, int count, string contextKey)
        {
            //contextKey is brandCode


            string filter = "1=1 ";
            string filterwrite = "1=1 ";

            filter += " AND MediaType='TVCR' AND ProdVersionName LIKE '" + prefixText + "%'";
            filterwrite += " AND MediaType='TVCR' AND ProdVersionName ='" + prefixText + "'";
            //get brand 

            //if (contextKey != null && contextKey != "" && contextKey != "0")
            //{
            //}
           



            if (count == 0) { count = 10; }
            List<string> items = new List<string>(count);

            DataTable dt = GetLookupDataSet().Tables[9];
           

            if (dt.Rows.Count > 0)
            {
                dt = RemoveDuplicateRows1(dt, "ProdVersionName");

            }

            DataRow[] drsUserWrite = dt.Select(filterwrite);
            try
            {
                if (drsUserWrite.Length == 1) //If user write and that item is in database
                {
                    HttpContext.Current.Session["TVCRVerUserWriteProductName"] = drsUserWrite[0][0];
                    HttpContext.Current.Session["TVCRVerUserWriteProductNameText"] = drsUserWrite[0][2];
                }
                else
                {
                    HttpContext.Current.Session["TVCRVerUserWriteProductName"] = -1;
                    HttpContext.Current.Session["TVCRVerUserWriteProductNameText"] ="";
                }
            }
            catch { }


            DataRow[] drs = dt.Select(filter);

            int counter = 0;
            foreach (DataRow dr in drs)
            {
                items.Add(AjaxControlToolkit.AutoCompleteExtender.CreateAutoCompleteItem(dr["ProdVersionName"].ToString(), dr["ProdVersionCode"].ToString()));


                if (++counter >= count) { break; }
            }

            return items.ToArray();
        }
          
        #endregion


        private void FillPrograms( int mediaTypeCode)
        {
            DataTable dt = GetLookupDataSet(mediaTypeCode).Tables[0];

            string filter = "1=1 ";
            string sort = "ProgramName";

            switch (lstMediaType.SelectedValue)
            {
                case "1":
                    {
                        filter += "AND TV=1";
                        break;
                    }
                case "3":
                    {
                        filter += "AND RD=1";
                        break;
                    }
                case "5":
                    {
                        filter += "AND CB=1";
                        break;
                    }
            }

            DataView dv = new DataView(dt, filter, sort, DataViewRowState.OriginalRows);

            lstProgram.DataSource = dv;
            lstProgram.DataBind();
            lstProgram.Items.Insert(0, new ListItem("- ALL -", "0"));
        }




        protected void btnSearch_Click(object sender, ImageClickEventArgs e)
        {

            DownloadOnly = chkDownload.Checked;
            if (DownloadOnly && (lstCategory.SelectedItem.Text == "- ALL -"))
            {
                AjaxFuncs.MsgBox(this.Page,
                                 "To download all the videos, audios, or images related to your category, u must select the category.");
                return;
            }

            DownloadOnlyAdvertiser = chkDownloadAdvertiser.Checked;
            if (DownloadOnlyAdvertiser && (lstAdvertiser.SelectedItem.Text == "- ALL -"))
            {
                AjaxFuncs.MsgBox(this.Page,
                                 "To download all the videos, audios, or images related to your advertiser, u must select the advertiser.");
                return;
            }


            bool tmp1 = DateTime.TryParse(calS.SelectedDate.ToShortDateString(), out sDate);
            bool tmp2 = DateTime.TryParse(calE.SelectedDate.ToShortDateString(), out eDate);

            if (sDate < Utility.ToDateTime("01/01/2000"))
                sDate = Utility.ToDateTime("01/01/2000");

            if (eDate < Utility.ToDateTime("01/01/2000"))
                eDate = Utility.ToDateTime("01/01/2000");
            if ((sDate.ToString() != "1/1/2000 12:00:00 AM") && (eDate.ToString() != "1/1/2000 12:00:00 AM"))
            {

                mediaTypeCode = Utility.ToInt(lstMediaType.SelectedValue);

                //mediaCode = Utility.ToInt(lstMedia.SelectedValue);
                foreach (ListItem itm in lstMedia.Items)
                {
                    if (itm.Selected)
                        mediaCodes += itm.Value + ",";
                }
                mediaCodes = mediaCodes.TrimEnd(',');


                programCode = Utility.ToInt(lstProgram.SelectedValue);

                sectorCode = Utility.ToInt(lstSector.SelectedValue);
                subSectorCode = Utility.ToInt(lstSubSector.SelectedValue);

                categoryCode = Utility.ToInt(lstCategory.SelectedValue);

                advertiserCode = Utility.ToInt(lstAdvertiser.SelectedValue);

                sector = lstSector.SelectedItem.Text;
                subsector = lstSubSector.SelectedItem.Text;
                category = lstCategory.SelectedItem.Text;
                advertiser = lstAdvertiser.SelectedItem.Text;
                agency = lstAgency.SelectedItem.Text;


                if (Utility.ToInt(acBrand.SelectedValue) == 0) //not selected by user
                {
                    try
                    {
                        if (Convert.ToInt32(Session["TVCRUserWriteProductName"].ToString()) != 0)
                        {

                            brandCode = Utility.ToInt(Session["TVCRUserWriteProductName"].ToString());
                            product = Session["TVCRUserWriteProductNameText"].ToString();
                        }
                    }
                    catch { }

                }
                else
                {
                    brandCode = Utility.ToInt(acBrand.SelectedValue);

                    TextBox txtBrand = (TextBox)acBrand.FindControl("tbAutoComplete");
                    product = txtBrand.Text;

                }

                DownloadOnlyProduct = chkDownloadProduct.Checked;

                if (DownloadOnlyProduct && (brandCode == 0))
                {
                    AjaxFuncs.MsgBox(this.Page,
                                     "To download all the videos, audios, or images related to your product, u must select the product.");
                    return;
                }



                productCode = Utility.ToInt(acProduct.SelectedValue);


                if (Utility.ToInt(acVersion.SelectedValue) == 0) //not selected by user
                {
                    try
                    {
                        if (Convert.ToInt32(Session["TVCRVerUserWriteProductName"].ToString()) != 0)
                        {

                            versionCode = Utility.ToInt(Session["TVCRVerUserWriteProductName"].ToString());
                            version = Session["TVCRVerUserWriteProductNameText"].ToString();
                        }
                    }
                    catch { }

                }
                else
                {
                    versionCode = Utility.ToInt(acVersion.SelectedValue);

                    TextBox txtVersion = (TextBox)acVersion.FindControl("tbAutoComplete");
                    version = txtVersion.Text;
                }


                agencyCode = Utility.ToInt(lstAgency.SelectedValue);

                sTime = Utility.ToInt(lstStartTime.SelectedValue);
                eTime = Utility.ToInt(lstEndTime.SelectedValue);

                sLength = tbDurationFrom.Text != "" ? Utility.ToInt(tbDurationFrom.Text) : 0;
                eLength = tbDurationTo.Text != "" ? Utility.ToInt(tbDurationTo.Text) : 0;

                posInBreak = tbPositionInBreak.Text != "" ? Utility.ToInt(tbPositionInBreak.Text) : 0;

                sPrice = tbPriceFrom.Text != "" ? Utility.ToInt(tbPriceFrom.Text) : 0;
                ePrice = tbPriceTo.Text != "" ? Utility.ToInt(tbPriceTo.Text) : 0;

                firstAppearanceOnly = chkFirstAppearance.Checked;




                //if (firstAppearanceOnly == false && (sDate == Utility.ToDateTime("01/01/2000") || eDate == Utility.ToDateTime("01/01/2000")) || eDate.Subtract(sDate).Days > 31)
                //{
                //    AjaxFuncs.MsgBox(this.Page, "You must select a date range of maximum 1 month");
                //    return;
                //}


                //if (firstAppearanceOnly && (sDate == Utility.ToDateTime("01/01/2000") || eDate.Subtract(sDate).Days != 0))
                //{
                //    AjaxFuncs.MsgBox(this.Page,
                //                     "To see the first appearance of a product, u must select the Date Range of only 1 Day. i.e. Select the same date as Start and End Date.");
                //    return;
                //}




                string cols = "";

                foreach (ListItem itm in lstFields.Items)
                {
                    if (itm.Selected)
                    {
                        cols += itm.Value + ", ";
                    }
                }

                if (cols.Contains(","))
                    cols = cols.Substring(0, cols.LastIndexOf(","));

                int DateS = DateTimeToInt(sDate);
                int DateE = DateTimeToInt(eDate);
                Session["SearchMediaCodes_TVRC"] = mediaCodes;

                Response.Redirect(Server.UrlPathEncode(string.Format("report-tvcr2.aspx?sd={0}&ed={1}&mtc={2}&mc={3}&prg={4}&s={5}&ss={6}&ss2={7}&cc={8}&adv={9}&brnd={10}&prod={11}&ver={12}&agn={13}&st={14}&et={15}&sl={16}&el={17}&pos={18}&sp={19}&ep={20}&fa={21}&cols={22}&down={23}&zs={24}&zss={25}&zc={26}&zad={27}&zag={28}&zp={29}&zve={30}&downpro={31}&downadv={32}", DateS, DateE, mediaTypeCode, chkAllMedia.Checked, programCode, sectorCode, subSectorCode, subSector2Code, categoryCode, advertiserCode, brandCode, productCode, versionCode, agencyCode, sTime, eTime, sLength, eLength, posInBreak, sPrice, ePrice, firstAppearanceOnly, cols, DownloadOnly, sector, subsector, category, advertiser, agency, product, version, DownloadOnlyProduct, DownloadOnlyAdvertiser)));



            }
            else
            {
                string script = "alert(\"Please select date first!\");";
                ScriptManager.RegisterStartupScript(this, this.GetType(), "ServerControlScript", script, true);
            }

        }
        public static int DateTimeToInt(DateTime theDate)
        {
            string month = theDate.Month.ToString();
            string Day = theDate.Day.ToString();
            month = (month.Length < 2) ? "0" + month : month;
            Day = (Day.Length < 2) ? "0" + Day : Day;
          int date=  Convert.ToInt32(theDate.Year.ToString() + month.ToString() + Day.ToString());
          return date;
        }
    }
}